'use strict';
import React, {Component} from 'react';
import {
	AppRegistry,
	StyleSheet,
	Image,
	Text,
	Alert,
	View
} from 'react-native';
import TypeButton from './TypeButton.js';
import InputButton from './InputButton.js';
import Style from './Style.js';
import SQLite from './SQLite.js';
import Payment from './Payment.js';
import Picker from 'react-native-picker';
import moment from 'moment';
const typeButtons= [
	[{title:'一般', icon: require('./images/ic_house.png')},{title:'用餐', icon: require('./images/ic_food.png')},{title:'交通', icon: require('./images/ic_transform.png')},{title:'服饰', icon: require('./images/ic_cloth.png')}],
	[{title:'日用品', icon: require('./images/ic_daily.png')},{title:'娱乐', icon: require('./images/ic_entertainment.png')},{title:'购物', icon: require('./images/ic_shopping.png')},{title:'住房', icon: require('./images/ic_house.png')}],
	[{title:'通讯', icon: require('./images/ic_communication.png')},{title:'学习', icon: require('./images/ic_study.png')},{title:'旅游', icon: require('./images/ic_transform.png')},{title:'零食', icon: require('./images/ic_food.png')}],
	[{title:'宠物', icon: require('./images/ic_other.png')},{title:'医疗', icon: require('./images/ic_medical.png')},{title:'数码', icon:require('./images/ic_tech.png')},{title:'化妆品', icon: require('./images/ic_beauty.png')}],
];

const inputButtons=[
	[{value:7,image:null},{value:8,image:null},{value:9,image:null},{value:'time',image:require('./images/ic_time.png')}],
	[{value:4,image:null},{value:5,image:null},{value:6,image:null},{value:'-',image:null}],
	[{value:1,image:null},{value:2,image:null},{value:3,image:null},{value:'+',image:null}],
	[{value:'.',image:null},{value:0,image:null},{value:'C',image:null},{value:'OK',image:null}],
];
var sqLite = new SQLite();
var db;
export default class Consumption extends Component {
    constructor(props) {
		super(props);
		this.state = {
			showText: '一般',
			icon: require('./images/ic_house.png'),
			inputValue: '',
			selectedSymbol: null,
			symbolFlag: false,
			date: new Date(),
			formula:'',
		};
	}

	static navigationOptions = {
        title: 'Expense',
    };

	showDatePicker() {
		var date = this.state.date;
		this.picker.showDatePicker(date, (d)=>{
			this.setState({date:d});
		});
	}

	componentWillUnmount(){
		// sqLite.close();
		Picker.hide();
	}

	componentWillMount(){
		if(!db){
			db=sqLite.open();
		}
		sqLite.createTable();
	}

    render() {
		return (
			<View style={Style.expenseContainer}>
				<View style={Style.expenseDisplayContainer}>
					{this.renderDisplayView()}
				</View>
				<View style={Style.expenseTypeContainer}>
					{this.renderTypeButtons()}
				</View>
				<View style={Style.expenseline}></View>
				<View style={Style.expenseInputContainer}>
					{this.renderInputButtons()}
				</View>
            </View>
		);
	}

	renderDisplayView() {
		return (
			<View style={Style.displayContainer}>
            	<Image source={this.state.icon} style={Style.displayIcon}/>
				<Text style={Style.displayText}>{this.state.showText}</Text>
				<Text style={Style.displayValue}>{this.state.inputValue}</Text>
			</View>
		);
	}

	renderTypeButtons() {
		let views = typeButtons.map((row, idx) => {
			let typeRow = row.map((typeValue, columnIdx) => {
				return <TypeButton
							key={'butt-' + columnIdx}
							value={typeValue.title}
							image={typeValue.icon}
							onPress={this.typeButtonPressed.bind(this, typeValue)}/>;
			});
			return <View style={Style.typeRow} key={'row-' + idx}>{typeRow}</View>
		});
		return views;
	}

	renderInputButtons() {
		let views = inputButtons.map((row, idx) => {
			let typeRow = row.map((typeValue, columnIdx) => {
				return <InputButton
							key={'butt-' + columnIdx}
							value={typeValue.value}
							image={typeValue.image}
							onPress={this.inputButtonPressed.bind(this, typeValue.value)}/>;
			});
			return <View style={Style.typeRow} key={'row-' + idx}>{typeRow}</View>
		});
		return views;
	}

	typeButtonPressed(input){
		this.setState(previousState => {
			return {
				showText: input.title,
				icon: input.icon
			};
		});
	}

	inputButtonPressed(input){
		 switch (typeof input) {
            case 'number':
                return this.handleNumberInput(input);
            default:
                return this.handleStringInput(input);
        }
	}

	handleNumberInput(num) {
		let s = num.toString();
		if (this.state.symbolFlag){
			this.setState({
				inputValue: s,
				formula: this.state.formula + this.state.selectedSymbol + s,
				symbolFlag: false,
			});
		} else {
			this.setState({
				inputValue: this.state.inputValue + s,
				formula: this.state.formula + s,
			});
		}
    }

	handleStringInput(str) {
        switch (str) {
            case '+':
            case '-':
				if(this.state.symbolFlag){
					this.setState({
						selectedSymbol:str,
					});
				} else {
					if (this.state.selectedSymbol != null) {
						let symbol = this.state.selectedSymbol,
						inputedValue = (eval(this.state.formula)).toString();
						this.setState({
							selectedSymbol: str,
							inputValue: inputedValue,
							symbolFlag: true,
						});
					} else {
						this.setState({
							selectedSymbol: str,
							previousInputValue: this.state.inputValue,
							symbolFlag: true,
						});
					}
				}
                break;

			case '.':
				this.setState({
					inputValue: this.state.inputValue + '.',
					formula: this.state.formula + '.',
				});
				break;

            case 'OK':
                let symbol = this.state.selectedSymbol,
                    inputValue = this.state.inputValue,
					formulas = this.state.formula;
				let payment = new Payment();
				payment.setType(this.state.showText);
                if (!symbol) {
                    payment.setMoney(inputValue);
                } else {
					payment.setMoney(eval(formulas));
					this.setState({
                    inputValue: eval(formulas),
					formula: eval(formulas),
                    selectedSymbol: null,
                	});
				}
				payment.setTime(this.state.date.valueOf());
				sqLite.savePayment(payment).then(()=>{
					Alert.alert("save Successful");
        		}).catch((e)=>{
					Alert.alert("fail");
					process.exit(1);
				});
                break;

            case 'C':
                this.setState({
					inputValue: '',
					formula:'',
					selectedSymbol: null,
					symbolFlag:false,
				});
                break;
			
			case 'time':
				this.showTimePicker();
				break;

        }
    }

	showTimePicker() {
		let year = this.state.date.getFullYear() + "年";
		let month = (this.state.date.getMonth() + 1) + "月";
		let day = this.state.date.getDate() + "日";
        Picker.init({
            pickerData: this._createDateData(),
            pickerToolBarFontSize: 16,
            pickerFontSize: 16,
            pickerFontColor: [0, 0 ,0, 1],
			pickerTitleText:'请选择日期',
			pickerConfirmBtnText:'确定',
			pickerCancelBtnText:'取消',
			pickerToolBarBg:[255,255,255,1],
			pickerBg:[255,255,255,1],
			wheelFlex:[1,1,1],
			selectedValue: [year,month,day],
            onPickerConfirm: (pickedValue, pickedIndex) => {
                console.log('date', pickedValue, pickedIndex);
				let timevalue = [...pickedIndex];
				let selectDate = new Date();
				selectDate.setFullYear(timevalue[0] + 2017);
				selectDate.setMonth(timevalue[1]);
				selectDate.setDate(timevalue[2] + 1);
				selectDate.setHours(2);
				this.setState({
					date: selectDate
				});
            },
            onPickerCancel: (pickedValue, pickedIndex) => {
                console.log('date', pickedValue, pickedIndex);
            },
            onPickerSelect: (pickedValue, pickedIndex) => {
                console.log('date', pickedValue, pickedIndex);
            }
        });
        Picker.show();
    }

	_createDateData() {
        let date = [];
        for(let i=2017;i<2050;i++){
            let month = [];
            for(let j = 1;j<13;j++){
                let day = [];
                if(j === 2){
                    for(let k=1;k<29;k++){
                        day.push(k+'日');
                    }
                    //Leap day for years that are divisible by 4, such as 2000, 2004
                    if(i%4 === 0){
                        day.push(29+'日');
                    }
                }
                else if(j in {1:1, 3:1, 5:1, 7:1, 8:1, 10:1, 12:1}){
                    for(let k=1;k<32;k++){
                        day.push(k+'日');
                    }
                }
                else{
                    for(let k=1;k<31;k++){
                        day.push(k+'日');
                    }
                }
                let _month = {};
                _month[j+'月'] = day;
                month.push(_month);
            }
            let _date = {};
            _date[i+'年'] = month;
            date.push(_date);
        }
        return date;
    }
}